﻿using System;
using Tiny.Imaging.Filter.PixelLibrary;

namespace Tiny.Imaging.Filter.PointFilter
{
    /// <summary>
    /// Factor reference:
    /// 25 = Photoshop 100
    /// -8.75 = Photoshop -50
    /// </summary>
    public class ContrastFilter : BaseFilter.BaseFilter
    {
        private int[] _mapping;

        public ContrastFilter(float factor = 1.0f, Func<int, int, int> blend = null, int opacity = 100)
            : base(blend, opacity)
        {
            factor = 1 + factor / 100.0f;
            PrePopulate(factor * factor);
        }

        public override int Process(Rgba rgba)
        {
            rgba.R = _mapping[rgba.R];
            rgba.G = _mapping[rgba.G];
            rgba.B = _mapping[rgba.B];

            return rgba.ToInteger();
        }

        private void PrePopulate(float factor)
        {
            _mapping = new int[256];

            for (int i = 0; i < 256; ++i)
            {
                _mapping[i] = Blend(i, MathLibrary.MathLibrary.Clamp((((i / 255.0f - 0.5f) * factor + 0.5f) * 255)));
            }
        }
    }
}